/**
 *
 * Startup https://github.com/taylorwrynn/Startup
 *
 * Copyright (C) 2017 Taylor Tang
 * 
 * Released under the Apache license v2 http://www.apache.org/licenses/
 *
 */

#import "UIScrollView+TXExtCocoa.h"
#import <objc/runtime.h>
#import "TXFire.h"
#import <Masonry/Masonry.h>
//#import "sys/utsname.h"

@implementation UIScrollView (TXExtCocoa)

@end

static const void * kZoomingView = &kZoomingView;

@implementation UIScrollView (TXHeaderZooming)

- (void)setTx_headerZoomingView:(UIView<TXZoomingView> *)view
{
    objc_setAssociatedObject(self, kZoomingView, view, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if (view.tx_height > 0)
    {
        CGFloat height = view.tx_height;
        [self addSubview:view];
        view.frame = CGRectMake(0, -height, self.tx_width, height);
        
        UIEdgeInsets insets = self.contentInset;
        insets.top += height;
        self.contentInset = insets;
    }
}

- (UIView<TXZoomingView> *)tx_headerZoomingView
{
    return objc_getAssociatedObject(self, kZoomingView);
}

- (void)tx_didScroll
{
    UIView *headerZoomingView = self.tx_headerZoomingView;
    if (!headerZoomingView) return;
    
    UIView *view = nil;
    
    if ([headerZoomingView conformsToProtocol:@protocol(TXZoomingView)] &&
        [headerZoomingView respondsToSelector:@selector(tx_viewFromZooming)])
    {
        view = [(UIView<TXZoomingView> *)headerZoomingView tx_viewFromZooming];
    }
    else
    {
        view = headerZoomingView;
    }
    
    CGFloat outTop = [self tx_offsetOutsideOfTop];
    
    if (outTop < 0)
    {
        CGFloat height = view.bounds.size.height;
        CGFloat scale = 1 - outTop / height;
        
        CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale);
        transform = CGAffineTransformTranslate(transform, 0, (outTop / 2) / scale);
        view.transform = transform;
    }
    else
    {
        view.transform = CGAffineTransformIdentity;
    }
}

@end
